<template>
  <div id="detail">
    <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav" />
    <scroll
      class="content"
      ref="scroll"
      :probe-type="3"
      @scroll="contentScroll"
    >
      <detail-swiper :top-images="topImages" />
      <detail-base-info :goods="goods" />
      <detail-shop-info :shop="shop" />
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad" />
      <detail-param-info ref="params" :param-info="paramInfo" />
      <detail-comment-info ref="comment" :comment-info="commentInfo" />
      <goods-list ref="recommend" :goods="recommends" />
    </scroll>
    <back-top v-show="isShowBackTop" @click.native="backTop" />
    <detail-bottom-bar @addToCart="addToCart" />
    <toast :message="message" :isShow="show" />
  </div>
</template>

<script>
import DetailNavBar from "./childComps/DetailNavBar";
import DetailSwiper from "./childComps/DetailSwiper";
import DetailBaseInfo from "./childComps/DetailBaseInfo";
import DetailShopInfo from "./childComps/DetailShopInfo";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo";
import DetailParamInfo from "./childComps/DetailParamInfo";
import DetailCommentInfo from "./childComps/DetailCommentInfo";
import DetailBottomBar from "./childComps/DetailBottomBar";
import Toast from "components/common/toast/Toast";

import Scroll from "components/common/scroll/Scroll";
import GoodsList from "components/content/goods/GoodsList";
import { debounce } from "common/utils";
import { backTopMixin } from "common/mixin";
import { mapGetters } from "vuex";

import {
  getDetail,
  Goods,
  Shop,
  GoodsParam,
  getRecommend,
} from "network/detail";
import { mapActions } from "vuex";

export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    DetailBottomBar,
    GoodsList,
    Toast,
    Scroll,
  },
  mixins: [backTopMixin],
  data() {
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [],
      getThemeTopY: null,
      currentIndex: 0,
      message: "",
      show: false,
    };
  },
  created() {
    //1.保存传入的iid
    // console.log(this.$route.params);
    this.iid = this.$route.params.iid;

    //2.根据iid请求数据
    getDetail(this.iid).then((res) => {
      //1.获取数据
      // console.log(res);
      //2.获取轮播图片
      const data = res.result;
      this.topImages = res.result.itemInfo.topImages;
      //   console.log(this.topImages);
      //3.获取商品信息
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );
      //4.创建店铺信息的对象
      this.shop = new Shop(data.shopInfo);

      //5.保存商品详情信息
      this.detailInfo = data.detailInfo;
      // console.log(this.detailInfo);

      //6.获取参数信息
      this.paramInfo = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );

      //7.读取评论信息
      if (data.rate.cRate !== 0) {
        this.commentInfo = data.rate.list[0];
      }
      //获取组件offsetTop
      this.$nextTick(() => {
        //获取的offsetTop值不正确的原因：
        // 1.this.$refs.params.$el未加载
        // 2.图片没有计算在内
        //3.所以不能在created,mounted,uptated,中拿offseTop
      });
    });
    //3.请求推荐数据
    getRecommend().then((res) => {
      // console.log(res);
      this.recommends = res.data.list;
    });
    this.getThemeTopY = debounce(() => {
      //获取组件offsetTop
      this.themeTopYs = [];
      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.params.$el.offsetTop - 44);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop - 44);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop - 44);
      this.themeTopYs.push(Number.MAX_VALUE);
      // console.log(this.themeTopYs);
    }, 100);
  },
  mounted() {
    // console.log("mounted");
  },
  updated() {
    // console.log("updated");
  },
  methods: {
    ...mapActions(["addCart"]),
    imageLoad() {
      this.$refs.scroll.refresh();
      // console.log("图片加载完成");
      this.getThemeTopY();
    },
    titleClick(index) {
      // console.log(index);
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 100);
    },
    contentScroll(position) {
      // console.log(position);
      //获取Y值
      const positionY = -position.y;
      //对比
      let length = this.themeTopYs.length;
      for (let i = 0; i < length - 1; i++) {
        // if (
        //   (this.currentIndex !== i &&
        //     i < length - 1 &&
        //     positionY >= this.themeTopYs[i] &&
        //     positionY < this.themeTopYs[i + 1]) ||
        //   (i === length - 1 && positionY >= this.themeTopYs[i])
        // )
        //通过给数组末尾加一个最大数字，简化判断
        if (
          positionY >= this.themeTopYs[i] &&
          positionY < this.themeTopYs[i + 1]
        ) {
          // console.log(i);
          this.currentIndex = i;
          //传给nav组件
          this.$refs.nav.currentIndex = this.currentIndex;
        }
      }
      //回到顶部
      this.isShowBackTop = -position.y > 2000;
    },
    addToCart() {
      // console.log("加入购物车");
      //1.获取购物车需要展示的信息
      const product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.newPrice = this.goods.realPrice;
      product.iid = this.iid;
      //2.vuex保存购物车数据
      //虽然可以这样添加，但是做好不要
      // this.$store.cartList.push(product);
      // this.$store.commit("addCart", product);
      // this.$store.dispatch("addCart", product);
      //3.添加到购物车成功(通过Promise回调函数)
      //添加购物车弹窗：掌握：①actions可以返回一个promise ②mapActions的映射关系
      this.addCart(product).then((res) => {
        this.show = true;
        this.message = res;
        // console.log(res);
        setTimeout(() => {
          this.show = false;
          this.message = "";
        }, 1500);
      });
      // this.$store.dispatch("addCart", product).then((res) => {
      //   console.log(res);
      // });
    },
  },
};
</script>

<style scoped>
#detail {
  position: relative;
  height: 100vh;
  z-index: 9;
  background-color: #fff;
}
.detail-nav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}
.content {
  height: calc(100% - 100px);
}
</style>